package com.simon.mctm.biz.sys.controller;

import com.simon.mctm.base.response.DoResponse;
import com.simon.mctm.biz.sys.bean.User;
import com.simon.mctm.biz.sys.service.UserService;
import com.simon.mctm.exception.CheckException;
import com.simon.mctm.exception.OperationFailedException;
import com.simon.mctm.token.Auth;
import com.simon.mctm.token.TokenUtil;
import com.simon.mctm.token.TokenValidate;
import com.simon.mctm.utils.Md5Utils;
import com.simon.mctm.utils.SystemCode;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author Jiajie.Mao
 * @date 2018/6/15 13:42
 **/
@RestController
@Api(description = "令牌")
@RequestMapping("/sys")
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private TokenUtil tokenUtil;

    @ApiOperation(value = "获取身份令牌", notes = "获取身份令牌")
    @ApiResponse(code = SystemCode.SYSTEM_SUCESS_CODE, message = "OK", response = DoResponse.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String")
    })
    @PostMapping("/auth")
    public DoResponse auth(@RequestParam String username, @RequestParam String password) {
        if (username == null || "".equals(username)) {
            throw new CheckException("用户名不能为空");
        }
        User user = userService.getUserByUsername(username);
        //判断用户是否存在
        if (user == null) {
            throw new OperationFailedException("用户不存在");
        }

        //判断用户名和密码是否匹配
        if (!Md5Utils.validPassword(password, user.getPassword())) {
            throw new OperationFailedException("用户名和密码错误");
        }

        //获取身份令牌
        Auth auth = tokenUtil.createToken(username);
        return new DoResponse(auth);
    }


    @ApiOperation(value = "注销身份令牌", notes = "注销身份令牌")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "String")
    })
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @TokenValidate
    public DoResponse logout(@RequestParam String token) {
        if (token == null || "".equals(token)) {
            throw new CheckException("token不能为空");
        }
        if (tokenUtil.deleteToken(token)) {
            return new DoResponse("注销成功");
        } else {
            throw new OperationFailedException("注销失败");
        }
    }
}
